<?php
namespace frontend\controllers;

use common\components\FrontBaseController;
use frontend\models\NewProject;
use Yii;
use \common\helps\tools;
use \common\helps\code;
use yii\db\Query;
use common\helps\detection;
use yii\db\Exception;
use \common\models\UploadForm;
use common\helps\qiniu;

/**
 * User controller
 */
class MovieController extends FrontBaseController
{

    public $modelClass = 'frontend\models\MovieCollege';
    public function init()
    {
        parent::init();
    }

    /*
     * 影视学堂列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionMovieList()
    {
        $model = new \frontend\models\MovieCollege();
        $postsJoin = new \frontend\models\PostsJoin();
        $request =$this->request;
        //$params = $request->queryParams;
        $params = $request->bodyParams;
        $total = $model::selectData($params,'`id`,`title`,`banner`,`play_num`,`created_at`');
        foreach ($total as $k => $v){
            $total[$k]['posts_num'] = count($postsJoin::selectData('`posts_join`.`id`',['movie_id' => $v['id']]));
        }
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);

        return code::success($res);
    }

    /*
     * 详情
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionMovieDetail(){
        $model = new \frontend\models\MovieCollege();
        $request =$this->request;
        $params = $request->bodyParams;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $data = $model::findOneData($params['id'],'`id`,`title`,`describe`,`video`,`play_num`,`created_at`');
            $res = $model::saveData($params['id']);
            if ($res && $data) {
                $transaction->commit();
                return code::success($data);
            }
        } catch (Exception $e) {
            $transaction->rollBack();
            throw new Exception($e->getMessage());
        }
        return code::success($data);
    }

    /*
     * 点赞/收藏
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionClickLike(){
        $model = new \frontend\models\PostsCollect();
        $posts = new \frontend\models\Posts();
        $task = new \frontend\models\Task();
        $member = new \frontend\models\Member();
        $int = new \frontend\models\IntLog();
        $redis = Yii::$app->cache;
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        if($params['is_click']=='yes'){
            $row = $posts::findOne(['id' => $params['posts_id'],'status' => 3]);
        }else{
            $row = $posts->find()->where(['id'=>$params['posts_id'],'status'=>3])->asArray()->one();
        }

        if(empty($row)){
            return code::error('','该信息不存在或已被删除');
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if($params['is_click']=='yes'){
                if($params['type'] == 'like'){
                    $day = $redis->get('dayClick'.date('Y-m-d').$member_info['id'].'like');
                }else{
                    $day = $redis->get('dayClick'.date('Y-m-d').$member_info['id'].'collect');
                }
                if($day === false){
                    if($params['type'] == 'like') {
                        $task_info = $task::findOne(['id' => 4]);
                    }else{
                        $task_info = $task::findOne(['id' => 5]);
                    }
                    $idata = [
                        'member_id' => $member_info['id'],
                        'task_id' => $task_info['id'],
                        'int' => $task_info['integral'],
                        'type' => 1,
                    ];
                    $intLog = $int::addData($idata);

                    $integral = $member_info['integral'] + $task_info['integral'];
                    $addInt = $member::saveData($member_info['id'],['integral' => $integral]);
                    $member_info['integral'] = $integral;
                    $redis->hset('member_info', $member_info['token'], json_encode($member_info));
                    if($params['type'] == 'like') {
                        $redis->set('dayClick' . date('Y-m-d') . $member_info['id'] . 'like', date('Y-m-d H:i:s'));
                    }else{
                        $redis->set('dayClick' . date('Y-m-d') . $member_info['id'] . 'collect', date('Y-m-d H:i:s'));
                    }
                }else{
                    $intLog = 1;
                    $addInt = 1;
                }
            }else{
                $intLog = 1;
                $addInt = 1;
            }

            $data = [
                'posts_id' => $params['posts_id'],
                'member_id' => $member_info['id'],
                'type' => $params['type'],
                'is_click' => $params['is_click'],
            ];
            $res = $model::like($data);
            if ($res && $intLog && $addInt) {
                $transaction->commit();
                return code::success(true);
            }
        } catch (Exception $e) {
            $transaction->rollBack();
            return $e->getMessage();
        }
    }

    /*
     * 讨论列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionPostsList()
    {
        $model = new \frontend\models\Posts();
        $request =$this->request;
        //$params = $request->queryParams;
        $params = $request->bodyParams;
        $member_info = tools::getMemberInfoByToken();
//        if(empty($params['movie_id'])){
//            return code::error('mistake');
//        }
        $params['my_posts'] = 1;
        $params['member_id'] = empty($member_info['id'])?'':$member_info['id'];
        $params['auth'] = 1;
        $total = $model::selectData($params,'`posts`.`id`,`posts`.`title`,`posts`.`img`,`posts`.`set_posts_id`,`posts`.`created_at`,`m`.`id` as `member_id`,`m`.`username`,`m`.`head_img`');
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        return code::success($res);
    }

    /*
     * 发帖
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionAddPosts()
    {
        $model = new \frontend\models\Posts();
        $pjoin = new \frontend\models\PostsJoin();
        $member_info = $this->member_info;
        $request = $this->request;
        $params = $request->bodyParams;
        if ($model->load($params, '')) {
            if ($model->validate()) {
                if(empty($params['movie_id'])){
                    return code::error('mistake');
                }
                if(empty(trim($params['describe'])) && empty($params['img'])){
                    return code::error('','内容不能为空');
                }
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $params['set_posts_id'] = $member_info['id'];
                    $params['set_posts_name'] = $member_info['username'];
                    $movie_id = $params['movie_id'];
                    unset($params['movie_id']);
                    $params['title'] = trim($params['title']);
                    $params['describe'] = trim($params['describe']);
                    $params['type'] = 1;
                    if(!empty($params['title'])){
                        //文本检测敏感词
                        $detection = new detection();
                        $check_res=$detection->checkWord($params['title']);
                        if($check_res['errcode']!=0){
                            return code::error('error','帖子标题含有敏感词汇');
                        }
                    }
                    if(!empty($params['describe'])){
                        //文本检测敏感词
                        $detection = new detection();
                        $check_res=$detection->checkWord($params['describe']);
                        if($check_res['errcode']!=0){
                            return code::error('error','帖子内容含有敏感词汇');
                        }
                    }
                    $res = $model->saveInfo('create', $params);
                    $data['posts_id'] = $res;
//                    $data['group_id'] = !empty($params['group_id'])?$params['group_id']:'';
//                    $data['item_id'] = !empty($params['item_id'])?$params['item_id']:'';
                    $data['movie_id'] = !empty($movie_id)?$movie_id:'';
                    $rat = $pjoin->saveInfo('create',$data);
                    if (empty($res['error']) && empty($rat['error'])) {
                        $transaction->commit();
                        return code::success(true);
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                    throw new Exception($e->getMessage());
                }
            } else {
                $error = array_values($model->getErrors());
                return code::error('', $error[0][0]);
            }
        }
    }

    /**
     * 用户发帖图片鉴别上传
     * @author hey_heyang(635870453@qq.com)
     * @return json
     */
    public function actionPostsImgUpload()
    {
        $model = new UploadForm();
        $files = $_FILES['file'];
        if(empty($files)){
            return code::error('error','未获取到文件对象');
        }
        //验证图片是否合规
        $detection = new detection();
        $check_res=$detection->checkImg( new \CURLFile($files['tmp_name']));
        if($check_res==false){
            return code::error('error','操作失败');
        }
        if(($check_res['errcode']!=0)){
            return code::error('error','图片含有不合规内容');
        }

        $model->file =$files;
        $dir=UPLOADS.'member/posts/';
        $res = $model->upload($dir,$files);
        if($res){
            $qiniu = new qiniu();
            $sExtension = strrchr($files['name'],'.');
            $time=tools::msectime();
            $file_name='usersPost/'.$time.$sExtension;
            $data_res=$qiniu->uploadByQiNiu($dir.$res,$file_name);
            @unlink($dir.$res);
            if(empty($data_res['key'])){
                return code::error('error','上传失败');
            }else{
                return code::success(array('img_url'=>$data_res['key']));
            }

        }else{
            return code::error('error','图片本地上传失败');
        }

    }

    /*
     * 帖子详情
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionPostsDetail()
    {
        $model = new \frontend\models\Posts();
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = tools::getMemberInfoByToken();

        $data = $model::findOneData($params['posts_id'],'`posts`.`id`,`posts`.`title`,`posts`.`status`,`posts`.`describe`,`posts`.`img`,`m`.`id` as `member_id`,`m`.`username`,`m`.`head_img`,`posts`.`created_at`',$member_info['id']);
        if(empty($data) || $data['status'] != 3){
            return code::error('','帖子正在审核中');
        }
        return code::success($data);
    }

    /*
     * 评论列表
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionCommentList()
    {
        $model = new \frontend\models\Comment();
        $request =$this->request;
        $params = $request->bodyParams;

        $total = $model::findAllData(['posts_id' => $params['posts_id']],'`m`.`username`,`m`.`head_img`,`comment`.`comment`,`comment`.`created_at`');
        $res = tools::getPageData($total,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        return code::success($res);
    }

    /*
     * 评论
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionAddComment()
    {
        $model = new \frontend\models\Comment();
        $posts = new \frontend\models\Posts();
        $notice = new \frontend\models\Notice();
        $request =$this->request;
        $params = $request->bodyParams;
        $member_info = $this->member_info;

        $posts_member = $posts::findOne(['id' => $params['posts_id']]);
        if(empty($posts_member)){
            return code::error('','帖子id错误');
        }
        $data = [
            'posts_id' => $params['posts_id'],
            'comment' => trim($params['comment']),
            'member_id' => $member_info['id'],
            'member_name' => $member_info['username'],
        ];
        if(empty($data['comment'])){
            return code::error('','评论内容不能为空');
        }
        if(!empty($data['comment'])){
            //文本检测敏感词
            $detection = new detection();
            $check_res=$detection->checkWord($data['comment']);
            if($check_res['errcode']!=0){
                return code::error('error','评论内容含有敏感词汇');
            }
        }
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $res = $model::addData($data);
            $row = $posts::addNum($params['posts_id']);
            if ($res && $row) {
                $transaction->commit();
                return code::success(true);
            }
        } catch (Exception $e) {
            $error = $e->getMessage();
            $transaction->rollBack();
        }
        return code::error('error');
    }

    /*
     * 电影排行
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionCatchMovie()
    {
        $redis = Yii::$app->cache;
        $maoyan_data = json_decode($redis->get('maoYan'),true);
        if(empty($maoyan_data)){
           $maoyan_data=$this->getMaoYanByCurl();
            if(empty($maoyan_data)){
                $maoyan_data=$this->getMaoYanByPy();
            }
            $redis->set('maoYan',json_encode($maoyan_data),60);
        }
        return code::success($maoyan_data);
    }

    /**
     * 获取首页实时票房数据by curl
     * @author hey_heyang(635870453@qq.com)
     * @return json
     */
    public  function  getMaoYanByCurl(){
        $model = new NewProject();
        $data = $model->getMovieBoxOffice();
        $res = [];
        for ($i = 0;$i < 10;$i++){
            $res[] = $data['data']['list'][$i];
        }
        return $res;
    }

    /**
     * 获取首页实时票房数据 py
     * @author hey_heyang(635870453@qq.com)
     * @return json
     */
    public function getMaoYanByPy()
    {
        $row = file_get_contents('http://47.99.178.80:8001/maoyan/');
        $row = json_decode($row,true);
        $res = [];
        for ($i = 0;$i < 10;$i++){
            $res[] = $row['data']['list'][$i];
        }
        return $res;
    }

    /*
     * 网络电影排行
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionCatchInternetMovie()
    {
        $model = new \frontend\models\MovieInternet();
        $res = $model::selectFieldData([],'*');
        $row = json_decode($res[0]['data'],true);
        return code::success($row);
    }

    /*
     * 网络电影排行
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function actionAddMovie(){
        $model = new \frontend\models\MovieInternet();
        $res = $this->getGuDuoByPy();
        $row = $model::addData(['data' => json_encode($res)]);
        return code::success($row);
    }

    public function getGuDuoByPy()
    {
        $row = file_get_contents('http://47.99.178.80:8001/guduo/');
        $row = json_decode($row,true);
        $res = [];
        for ($i = 0;$i < 10;$i++){
            $res[] = $row['data'][$i];
        }
        return $res;
    }


}
